package com.zhj.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhj.springbootinit.annotation.AuthCheck;
import com.zhj.springbootinit.bizmq.BIMessageProducer;
import com.zhj.springbootinit.common.BaseResponse;
import com.zhj.springbootinit.common.DeleteRequest;
import com.zhj.springbootinit.common.ErrorCode;
import com.zhj.springbootinit.common.ResultUtils;
import com.zhj.springbootinit.constant.CommonConstant;
import com.zhj.springbootinit.constant.UserConstant;
import com.zhj.springbootinit.exception.BusinessException;
import com.zhj.springbootinit.exception.ThrowUtils;
import com.zhj.springbootinit.manager.AIManager;
import com.zhj.springbootinit.manager.RedisLimiterManager;
import com.zhj.springbootinit.model.dto.chart.ChartAddRequest;
import com.zhj.springbootinit.model.dto.chart.ChartEditRequest;
import com.zhj.springbootinit.model.dto.chart.ChartQueryRequest;
import com.zhj.springbootinit.model.dto.chart.ChartUpdateRequest;
import com.zhj.springbootinit.model.dto.file.UploadChartRequest;
import com.zhj.springbootinit.model.entity.Chart;
import com.zhj.springbootinit.model.entity.User;
import com.zhj.springbootinit.model.vo.BiResponse;
import com.zhj.springbootinit.service.ChartService;
import com.zhj.springbootinit.service.UserService;
import com.zhj.springbootinit.utils.ExcelUtils;
import com.zhj.springbootinit.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/lizhj">HaoJie</a>
 * @from <a href="https://zhj.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private AIManager aiManager;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private BIMessageProducer biMessageProducer;

    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getChartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param chartQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<Chart>> listChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                       HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<Chart>> listMyChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                       HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    // endregion

//    /**
//     * 分页搜索（从 ES 查询，封装类）
//     *
//     * @param chartQueryRequest
//     * @param request
//     * @return
//     */
//    @PostMapping("/search/page/vo")
//    public BaseResponse<Page<Chart>> searchChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
//            HttpServletRequest request) {
//        long size = chartQueryRequest.getPageSize();
//        // 限制爬虫
//        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
//        Page<Chart> chartPage = chartService.searchFromEs(chartQueryRequest);
//        return ResultUtils.success(chartPage);
//    }

    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    public QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        Long id = chartQueryRequest.getId();
        // test
        String name = chartQueryRequest.getName();
        String goal = chartQueryRequest.getGoal();
        String chartType = chartQueryRequest.getChartType();
        Long userId = chartQueryRequest.getUserId();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();

        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.eq(id != null && id > 0, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(goal), "goal", goal);
        queryWrapper.eq(StringUtils.isNotBlank(chartType), "chartType", chartType);
        queryWrapper.eq(userId != null && userId > 0, "userId", id);
        queryWrapper.eq("isDelete", 0);

        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 生成图表（异步） 线程池
     *
     * @param multipartFile
     * @param uploadChartRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async")
    public BaseResponse<BiResponse> genChartByAIAsync(@RequestPart("file") MultipartFile multipartFile,
                                                      UploadChartRequest uploadChartRequest, HttpServletRequest request) {
        String name = uploadChartRequest.getName();
        String goal = uploadChartRequest.getGoal();
        String chartType = uploadChartRequest.getChartType();
        User loginUser = userService.getLoginUser(request);

        // 字段校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isBlank(chartType), ErrorCode.PARAMS_ERROR, "图表类型为空");
        ThrowUtils.throwIf(StringUtils.isBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长");

        // 文件校验
        long fileSize = multipartFile.getSize();

        final long maxfilSize = 30 * 1024 * 1024L;
        ThrowUtils.throwIf(fileSize > maxfilSize, ErrorCode.PARAMS_ERROR, "文件过大,超过30M");

        String originalFilename = multipartFile.getOriginalFilename();

        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> validSuffix = Arrays.asList("xls", "xlsx", "csv", "xlsm", "xlsb", "xltx", "xltm");
        ThrowUtils.throwIf(!validSuffix.contains(suffix), ErrorCode.PARAMS_ERROR, "文件类型不符合上传要求");

        StringBuilder userInput = new StringBuilder();
//        // 1.系统预设
//        userInput.append("你是一个高级数据分析师,下面我将给你分析目标和数据,请告诉我可靠的分析结论").append("\n");
        // 2.分析目标
        userInput.append("分析需求:").append("\n");

        String targetText = goal;
        targetText += ",请使用" + chartType;
        userInput.append(targetText).append("\n");

        // 3.数据
        String dataText = ExcelUtils.ExcelToCsv(multipartFile);
        userInput.append("数据:").append("\n").append(dataText);

        // 限流器判断，每个用户一个限流器  方法+用户
        redisLimiterManager.doRateLimit("genChartByAI-" + String.valueOf(loginUser.getId()));

        // 插入数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartType(chartType);
        chart.setChartData(dataText);
        chart.setStatus("wait");
        chart.setUserId(loginUser.getId());
        chartService.save(chart);

        BiResponse biResponse = new BiResponse();
        biResponse.setChartId(chart.getId());

        // 任务队列满了之后，抛异常的情况
        CompletableFuture.runAsync(() -> {
            Chart updateChart = new Chart();
            updateChart.setId(chart.getId());
            updateChart.setStatus("running");

            // 修改状态
            boolean b = chartService.updateById(updateChart);
//            ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR, "Chart更新状态失败");
            if (!b) {
                handleUpdateChartError(chart.getId(), "Chart更新状态失败");
                return;
            }

            // 正式调用AI接口
            String resultText = aiManager.getMessageByAI(userInput.toString());

            String[] split = resultText.split("【【【【【");
            ThrowUtils.throwIf(split.length < 3, ErrorCode.OPERATION_ERROR, "AI响应错误，返回参数异常");
            String codeData = split[1].trim(); // echarts代码数据
            String resultData = split[2].trim(); // 分析结果数据

            Chart resultChart = new Chart();
            resultChart.setId(chart.getId());
            resultChart.setGenChart(codeData);
            resultChart.setGenResult(resultData);
            // todo 建议定义状态为枚举值
            resultChart.setStatus("succeed");
            boolean b1 = chartService.updateById(resultChart);
//            ThrowUtils.throwIf(!b1, ErrorCode.OPERATION_ERROR, "存储AI处理结果失败");
            if (!b1) {
                handleUpdateChartError(chart.getId(), "存储AI处理结果失败");
            }
        }, threadPoolExecutor);

        return ResultUtils.success(biResponse);
    }

    public void handleUpdateChartError(Long chartId, String execMessage) {
        Chart chart = new Chart();
        chart.setId(chartId);
        chart.setStatus("fail");
        chart.setExecMessage(execMessage);
        boolean updateResult = chartService.updateById(chart);
        if (!updateResult) {
            log.error("更新图表失败状态失败:" + chartId + "," + execMessage);
        }
    }

    /**
     * 生成图表（异步） 消息队列
     *
     * @param multipartFile
     * @param uploadChartRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/mq")
    public BaseResponse<BiResponse> genChartByAIMQ(@RequestPart("file") MultipartFile multipartFile,
                                                   UploadChartRequest uploadChartRequest, HttpServletRequest request) {
        String name = uploadChartRequest.getName();
        String goal = uploadChartRequest.getGoal();
        String chartType = uploadChartRequest.getChartType();
        User loginUser = userService.getLoginUser(request);

        // 字段校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isBlank(chartType), ErrorCode.PARAMS_ERROR, "图表类型为空");
        ThrowUtils.throwIf(StringUtils.isBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长");

        // 文件校验
        long fileSize = multipartFile.getSize();

        final long maxfilSize = 30 * 1024 * 1024L;
        ThrowUtils.throwIf(fileSize > maxfilSize, ErrorCode.PARAMS_ERROR, "文件过大,超过30M");

        String originalFilename = multipartFile.getOriginalFilename();

        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> validSuffix = Arrays.asList("xls", "xlsx", "csv", "xlsm", "xlsb", "xltx", "xltm");
        ThrowUtils.throwIf(!validSuffix.contains(suffix), ErrorCode.PARAMS_ERROR, "文件类型不符合上传要求");

        StringBuilder userInput = new StringBuilder();
//        // 1.系统预设
//        userInput.append("你是一个高级数据分析师,下面我将给你分析目标和数据,请告诉我可靠的分析结论").append("\n");
        // 2.分析目标
        userInput.append("分析需求:").append("\n");

        String targetText = goal;
        targetText += ",请使用" + chartType;
        userInput.append(targetText).append("\n");

        // 3.数据
        String dataText = ExcelUtils.ExcelToCsv(multipartFile);
        userInput.append("数据:").append("\n").append(dataText);

        // 限流器判断，每个用户一个限流器  方法+用户
        redisLimiterManager.doRateLimit("genChartByAI-" + String.valueOf(loginUser.getId()));

        // 插入数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartType(chartType);
        chart.setChartData(dataText);
        chart.setStatus("wait");
        chart.setUserId(loginUser.getId());
        boolean saveResult = chartService.save(chart);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "图表保存失败");
        Long newChartId = chart.getId();

        // 放到消息队列中，再根据chartid进行查询拼接
        // 之前这一步是放在线程池中做的
        biMessageProducer.sendMessage(String.valueOf(newChartId));

        BiResponse biResponse = new BiResponse();
        biResponse.setChartId(newChartId);

        // 任务队列满了之后，抛异常的情况
//        CompletableFuture.runAsync(() -> {}, threadPoolExecutor);


        return ResultUtils.success(biResponse);
    }

    /**
     * 生成图表（同步）
     *
     * @param multipartFile
     * @param uploadChartRequest
     * @param request
     * @return
     */
    @PostMapping("/gen")
    public BaseResponse<BiResponse> genChartByAI(@RequestPart("file") MultipartFile multipartFile,
                                                 UploadChartRequest uploadChartRequest, HttpServletRequest request) {
        String name = uploadChartRequest.getName();
        String goal = uploadChartRequest.getGoal();
        String chartType = uploadChartRequest.getChartType();
        User loginUser = userService.getLoginUser(request);

        // 校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isBlank(chartType), ErrorCode.PARAMS_ERROR, "图表类型为空");
        ThrowUtils.throwIf(StringUtils.isBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长");

        StringBuilder userInput = new StringBuilder();
//        // 1.系统预设
//        userInput.append("你是一个高级数据分析师,下面我将给你分析目标和数据,请告诉我可靠的分析结论").append("\n");
        // 2.分析目标
        userInput.append("分析需求:").append("\n");

        String targetText = goal;
        targetText += ",请使用" + chartType;
        userInput.append(targetText).append("\n");

        // 3.数据
        String dataText = ExcelUtils.ExcelToCsv(multipartFile);
        userInput.append("数据:").append("\n").append(dataText);

        // 正式调用接口
        String resultText = aiManager.getMessageByAI(userInput.toString());

        String[] split = resultText.split("【【【【【");
        ThrowUtils.throwIf(split.length < 3, ErrorCode.OPERATION_ERROR, "AI响应错误，返回参数异常");
        String codeData = handleCodeData(split[1]); // echarts代码数据
        String resultData = split[2].trim(); // 分析结果数据

        // 插入数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartType(chartType);
        chart.setChartData(dataText);
        chart.setGenChart(codeData);
        chart.setGenResult(resultData);
        chart.setUserId(loginUser.getId());
        chart.setStatus("succeed");

        chartService.save(chart);

        BiResponse biResponse = new BiResponse();
        biResponse.setGenChart(codeData);
        biResponse.setGenResult(resultData);
        biResponse.setChartId(chart.getId());


        return ResultUtils.success(biResponse);
    }

    private String handleCodeData(String str) {
        if (StringUtils.isNotBlank(str)) {
            int start = str.indexOf("{");
            int end = str.lastIndexOf("}");
            return str.substring(start, end + 1);
        }
        return "";
    }


}
